"""
OpenRouter API 封装

提供对 OpenRouter 服务的访问接口。
"""

import time
from typing import Any, Dict, Optional, Iterator

import openai
from openai import OpenAI

from .base import AIModel, ModelFactory
from ..utils.config import Config


class OpenRouterModel(AIModel):
    """OpenRouter 模型实现"""
    
    def __init__(self, config: Config) -> None:
        super().__init__(config)
        
        # 获取配置
        api_key = config.get_api_key("openrouter")
        base_url = config.get_base_url("openrouter")
        model = config.get_model("openrouter")
        
        if not api_key:
            raise ValueError("OpenRouter API密钥未设置")
        
        # 初始化OpenAI客户端
        self.client = OpenAI(
            api_key=api_key,
            base_url=base_url
        )
        self.model = model
        
        # 默认参数
        self.default_params = {
            "temperature": 0.7,
            "max_tokens": 2048,
            "top_p": 1.0,
            "frequency_penalty": 0.0,
            "presence_penalty": 0.0
        }
    
    def generate(self, prompt: str, stream: bool = False, **kwargs) -> str:
        """
        生成响应
        
        Args:
            prompt: 输入提示词
            stream: 是否使用流式API调用
            **kwargs: 其他参数
            
        Returns:
            生成的响应文本
        """
        try:
            # 合并参数
            params = self.default_params.copy()
            params.update(kwargs)
            
            if stream:
                # 使用流式API调用，但返回完整响应
                return self._generate_stream_complete(prompt, params)
            else:
                # 使用非流式API调用
                return self._generate_normal(prompt, params)
                
        except openai.AuthenticationError:
            raise ValueError("OpenRouter API密钥无效")
        except openai.RateLimitError:
            raise RuntimeError("API请求频率超限，请稍后重试")
        except openai.APIError as e:
            raise RuntimeError(f"OpenRouter API错误: {e}")
        except Exception as e:
            raise RuntimeError(f"请求失败: {e}")
    
    def _generate_normal(self, prompt: str, params: Dict[str, Any]) -> str:
        """使用非流式API生成响应"""
        # 发送请求
        response = self.client.chat.completions.create(
            model=self.model,
            messages=[
                {"role": "user", "content": prompt}
            ],
            **params
        )
        
        # 提取响应内容
        if response.choices and len(response.choices) > 0:
            return response.choices[0].message.content or ""
        else:
            return "未收到有效响应"
    
    def _generate_stream_complete(self, prompt: str, params: Dict[str, Any]) -> str:
        """使用流式API生成完整响应"""
        # 发送流式请求
        stream = self.client.chat.completions.create(
            model=self.model,
            messages=[
                {"role": "user", "content": prompt}
            ],
            stream=True,
            **params
        )
        
        # 收集所有流式响应片段
        complete_response = ""
        for chunk in stream:
            if chunk.choices and len(chunk.choices) > 0:
                delta = chunk.choices[0].delta
                if delta.content:
                    complete_response += delta.content
        
        return complete_response or "未收到有效响应"
    
    def generate_stream(self, prompt: str, **kwargs) -> Iterator[str]:
        """
        流式生成响应（返回迭代器）
        
        Args:
            prompt: 输入提示词
            **kwargs: 其他参数
            
        Yields:
            响应文本片段
        """
        try:
            # 合并参数
            params = self.default_params.copy()
            params.update(kwargs)
            
            # 发送流式请求
            stream = self.client.chat.completions.create(
                model=self.model,
                messages=[
                    {"role": "user", "content": prompt}
                ],
                stream=True,
                **params
            )
            
            # 处理流式响应
            for chunk in stream:
                if chunk.choices and len(chunk.choices) > 0:
                    delta = chunk.choices[0].delta
                    if delta.content:
                        yield delta.content
                        
        except openai.AuthenticationError:
            raise ValueError("OpenRouter API密钥无效")
        except openai.RateLimitError:
            raise RuntimeError("API请求频率超限，请稍后重试")
        except openai.APIError as e:
            raise RuntimeError(f"OpenRouter API错误: {e}")
        except Exception as e:
            raise RuntimeError(f"请求失败: {e}")
    
    def is_available(self) -> bool:
        """
        检查模型是否可用
        
        Returns:
            模型是否可用
        """
        try:
            # 尝试发送一个简单的测试请求
            self.generate("test", max_tokens=1)
            return True
        except Exception:
            return False
    
    def get_available_models(self) -> list:
        """
        获取可用的模型列表
        
        Returns:
            可用模型列表
        """
        try:
            response = self.client.models.list()
            return [model.id for model in response.data]
        except Exception:
            return []


# 注册到工厂
ModelFactory.register("openrouter", OpenRouterModel)
